function Store(options) {
  const defaults = {
    type: 'localStorage',
    nameSpace: '__local_store_',
  };
  const { type, nameSpace } = { ...defaults, ...options };
  this.store = window[type];
  this.nameSpace = nameSpace;
}

Store.prototype.set = function set(key, state) {
  this.store.setItem(
    this.nameSpace + key,
    JSON.stringify({
      default: state,
      typeof: Object.prototype.toString.call(state).slice(8, -1),
    })
  );
};

Store.prototype.get = function get(key) {
  try {
    return JSON.parse(this.store.getItem(this.nameSpace + key)).default;
  } catch (error) {
    // eslint-disable-next-line no-console
    console.log(error);
  }
};

Store.prototype.getKeys = function getKeys() {
  const len = this.store.length; // 获取长度
  const keys = [];
  for (let i = 0; i < len; i++) {
    const key = this.store.key(i);
    if (key.startsWith(this.nameSpace)) {
      keys.push(key.slice(this.nameSpace.length));
    }
  }
  return keys;
};

Store.prototype.remove = function remove(key) {
  const keys = this.getKeys();
  const getRemoveKeys = (key, defaults) => {
    if (typeof key === 'function') return getRemoveKeys(key(keys), defaults);
    if (typeof key === 'string') return [key];
    if (Array.isArray(key)) return key;
    return defaults;
  };
  const removeKeys = getRemoveKeys(key, keys);
  removeKeys.forEach(key => {
    this.store.removeItem(this.nameSpace + key);
  });
};

export default Store;
